<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    
    <script src="vue.js"></script>
    <script>

       //非父子组件的通信方法
       //1.先定义在VUE的原型上定义一个$bus属性 Vue.prototype.$bus
       //2.由发送方使用 this.$bus.$emit('sendtohead','i am from buttom')来发送带参数的函数
       //3.由接收方使用this.$bus.$on('sendtohead',val=> {
                    // this.msg=val;
                    // console.log(this);来收到传来的函数和参数

        Vue.prototype.$bus=new Vue();
        var myHeader={
            template:`<div >i am header  {{msg}}</div>`,

            data:function () {
              return  {msg:'123'}
            }
            
            ,
            
            created:function () {
                // this.$bus.$on('sendtohead',function () {
                //         //this area this leads to this.$bus.$on,not myHeader,so can not find  msg
                //     this.msg=val;
                //     console.log(this);
                // }
                // )

                    // use the arrow function, can change this leads to myHeader
                this.$bus.$on('sendtohead',val=> {
                    this.msg=val;
                    console.log(this);
                })
                
            }
        }
        
        var myBody={
            template:`<div >i am body</div>`,
        }
        var myButtom={
            template:`
            <div>
                <div>i am buttom</div>
                <button @click="send">click me send to header</button>

        </div>
            `,

            methods:{
                send:function(){
                    this.$bus.$emit('sendtohead','i am from buttom')
                }
            }
        }

        new Vue({
             el:'#app',
             components:{
                myHeader,
                myBody,
                myButtom

},
             template:`
             <div>
             <myHeader></myHeader>
             <myBody></myBody>
             <myButtom></myButtom>
             </div>
             `,

             

        })

    </script>
</body>
</html>